package com.enba.boot.payment.config;

import com.alipay.easysdk.factory.Factory;
import com.enba.boot.core.base.ShowBootInfo;
import com.enba.boot.payment.alipay.AliPayHelper;
import com.enba.boot.payment.properties.AliPayProperties;
import com.enba.boot.payment.properties.WechatPayProperties;
import com.enba.boot.payment.wechatpay.WechatPayHelper;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.http.HttpClient;
import com.wechat.pay.java.core.notification.NotificationConfig;
import javax.annotation.PostConstruct;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@EnableConfigurationProperties(value = {AliPayProperties.class, WechatPayProperties.class})
@Configuration
public class PayAutoConfiguration implements ShowBootInfo {

  @ConditionalOnProperty(prefix = "payment.alipay", name = "enable", havingValue = "true")
  @ConditionalOnClass(Factory.class)
  @Bean(initMethod = "checkAliPayProperties")
  public AliPayHelper aliPayHelper(AliPayProperties aliPaySetting) {
    return new AliPayHelper(aliPaySetting);
  }

  @ConditionalOnProperty(prefix = "payment.wechatpay", name = "enable", havingValue = "true")
  @ConditionalOnClass(HttpClient.class)
  @Bean(initMethod = "checkWechatPayProperties")
  public WechatPayHelper wechatPayProperties(
      WechatPayProperties wechatPayProperties, NotificationConfig wechatConfig) {
    return new WechatPayHelper(wechatPayProperties, wechatConfig);
  }

  @ConditionalOnProperty(prefix = "payment.wechatpay", name = "enable", havingValue = "true")
  @ConditionalOnClass(HttpClient.class)
  @Bean
  public NotificationConfig wechatConfig(WechatPayProperties nativeProperties) {
    return new RSAAutoCertificateConfig.Builder()
        .merchantId(nativeProperties.getMerchantId())
        .privateKeyFromPath(nativeProperties.getPrivateKeyPath())
        .merchantSerialNumber(nativeProperties.getMerchantSerialNumber())
        .apiV3Key(nativeProperties.getApiV3Key())
        .build();
  }

  @PostConstruct
  @Override
  public void showBootInfo() {
    ShowBootInfo.moduleMap.put("enba-boot-starter-payment", "enba-boot-starter-payment模块集成成功");
  }
}
